import datetime
import logging

from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import get_hexdigest, check_password

from models import User

class AppEngineBackend(object):
    """Authenticate using AppEngine.
    """

    def authenticate(self, username=None, password=None):
        # we're authenticate by using email, so the username is actually email
        email = username
        user = User.all().filter("email = ", email).get()
        if user:
            if password and user.check_password(password):
                return user
        return None

    def get_user(self, user_id):
        return User.get_by_id(user_id)


def get_user(userid):
    """Returns a User object from an id (User.id). Django's equivalent takes
    request, but taking an id instead leaves it up to the developer to store
    the id in any way they want (session, signed cookie, etc.)
    """
    if not userid:
        return AnonymousUser()
    return AppEngineBackend().get_user(userid) or AnonymousUser()
